package com.jackeysun.log

import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jackeysun.common.AbsAdapter
import com.jackeysun.common.IData
import com.jackeysun.log.databinding.ActivityLogBinding
import com.jackeysun.log.databinding.ActivityLogFileBinding
import com.jackeysun.log.databinding.ItemLogBinding
import java.io.File

class LogFileActivity : AppCompatActivity() {

    private lateinit var mBinding: ActivityLogFileBinding
    private val data = mutableListOf<LogFileData>()

    private lateinit var adapter: AbsAdapter<LogFileData>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityLogFileBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        adapter = AbsAdapter { adapter, view, position ->
            share(adapter.getItem(position).file)
        }
        adapter.addLayout(0, R.layout.item_log)
        adapter.addClickId(R.id.tv)
        adapter.data = data
        mBinding.rv.adapter = adapter
        mBinding.rv.layoutManager = LinearLayoutManager(this)
        mBinding.rv.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        val files = LogConfig.file?.getLogFileList()
        files?.forEach {
            data.add(LogFileData(it))
        }
        adapter.notifyDataSetChanged()
    }

    private fun share(file: File?){
        if (file?.exists() == false) {
            Toast.makeText(this,"文件不存在",Toast.LENGTH_LONG).show()
            return
        }
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "text/plain"
        val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(
                this,
                "${this.application.packageName}.fileprovider",
                file ?: return
            )
        } else {
            Uri.fromFile(file)
        }
        intent.putExtra(Intent.EXTRA_STREAM, uri)
        startActivity(Intent.createChooser(intent, "未找到可分享的应用"))
    }
}

data class LogFileData(val file: File) : IData {
    override fun bind(holder: RecyclerView.ViewHolder) {
        val itemLogBinding = ItemLogBinding.bind(holder.itemView)
        itemLogBinding.tv.text = file.name
    }

}